package com.itheima.publisher;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class ThreadDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {


        /*
            String getName()                    返回此线程的名称
            void setName(String name)           设置线程的名字（构造方法也可以设置名字）
            static Thread currentThread()       获取当前线程的对象
            static void sleep(long time)        让线程休眠指定的时间，单位为毫秒
            setPriority(int newPriority)        设置线程的优先级
            final int get Priority()            获取线程的优先级
            final void setDaemon(boolean on)    设置为守护线程，非守护线程执行完毕后，守护线程会自动结束
            public static void yield()          出让线程/礼让线程
            public final void join()            插入线程/插队线程
         */

        /* java是单继承的，MyThread不能继承多个类，扩展性差 */
        class MyThread extends Thread {
            @Override
            public void run() {
                for(int i = 0; i < 100; i++){
                    System.out.println("线程" + getName() + "正在执行...");
                }
                try {
                    sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }
        Thread t3 = new MyThread();
        t3.start();


        /* 扩展性强 */
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 100; i++) {
                    System.out.println("线程" + Thread.currentThread().getName() + "正在执行...");
                }
            }
        });
        t1.start();


        /* 扩展性强，线程返回结果 */
        FutureTask<String> task = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                for(int i = 0; i < 100; i++){
                    System.out.println("线程" + Thread.currentThread().getName() + "正在执行...");
                }
                return "hello";
            }
        });
        Thread t4 = new Thread(task);
        t4.start();
        System.out.println(task.get());
    }
}
